﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Example2.Model
{

    /***
     * Denna klass representerar de logiska regler som finns i spelet
     * Klassen aggregerar objekt av andra model-klasser som Ball, Level, Pad
     * 
     * Klassen har också ett publikt interface mot controllern
     * 
     */ 
    class ArkanoidGame
    {
        //Spelets beståndsdelar
        public Pad m_pad = new Pad();
        public Level m_level = new Level();
        public Ball m_ball = new Ball();

        /**
         * Metod för att uppdatera spellogiken
         */
        internal void UpdateSimulation(float a_elapsedTimeSeconds)
        {
           
            m_pad.Update(a_elapsedTimeSeconds);

            m_ball.Update(a_elapsedTimeSeconds);

            m_ball.CollideWalls(Level.LEVEL_WIDTH);
            
            

            Vector2 normal = new Vector2();
            if (m_level.doBallAndTilesColliding(m_ball.m_centerPosition, m_ball.m_radius, out normal))
            {
                doCollide(m_ball, normal);
                
            }

            if (m_pad.isBallAndPadColliding(m_ball.m_centerPosition, m_ball.m_radius))
            {
                doCollide(m_ball, m_pad.getNormalAt(m_ball.m_centerPosition));

                if (m_ball.m_centerPosition.Y + m_ball.m_radius > m_pad.m_centerTopPosition.Y)
                {
                    m_ball.m_centerPosition.Y = m_pad.m_centerTopPosition.Y - m_ball.m_radius;
                }
                if (m_ball.m_velocity.Y > 0)
                {
                    m_ball.m_velocity.Y = -m_ball.m_velocity.Y;
                }
            }
        }

      
        

        private void doCollide(Ball a_ball, Microsoft.Xna.Framework.Vector2 a_normal)
        {
            //move back to noncolliding position
            a_ball.m_centerPosition = a_ball.m_oldCenterPosition;

            //http://nehe.gamedev.net/tutorial/collision_detection/17005/
            //R= 2*(-I dot N)*N + I
            Vector2 reflection = 2.0f * ( - Vector2.Dot(a_ball.m_velocity, a_normal ) * a_normal) + a_ball.m_velocity;

            a_ball.m_velocity = reflection;
        }

        internal void StartNewGame()
        {
            m_ball = new Ball();
        }
    }
}
